package com.zhao.util;

import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.UUID;

/**
 * 检验signature
 * @author zhaowj
 * @date2018年1月22日 下午8:12:24
 */
public class SignUtil {
	  private static String token = "mobileWx";
	  
      private static final FieldPosition HELPER_POSITION = new FieldPosition(0);
      private final static Format dateFormat = new SimpleDateFormat("MMddHHmmssS");
      private final static NumberFormat numberFormat = new DecimalFormat("0000");
      private static int seq = 0;
      private static final int MAX = 9999;
	   
	    public static boolean checkSignature(String signature, String timestamp, String nonce) {  
	        boolean result = false;  
	   
	        String[] array = new String[]{token, timestamp, nonce};  
	        Arrays.sort(array); //按字典排序
	   
	        String str = array[0].concat(array[1]).concat(array[2]);  
	   
	        String sha1Str = null;  
	        try {  
	            MessageDigest md = MessageDigest.getInstance("SHA-1");  
	            byte[] digest = md.digest(str.getBytes());  
	            sha1Str = byte2str(digest);  
	        }  
	        catch(Exception e) {  
	        	
	        }  
	        if(sha1Str != null &&  sha1Str.equals(signature)) {  
	            result = true;  
	        }  
	   
	        return result;  
	    }  
	   
	    /**
	     * 获取加密后的字符串
	     * @param array
	     * @return
	     */
	    public static String byte2str(byte[] array) {  
	        StringBuffer hexstr = new StringBuffer();  
	        String shaHex="";  
	        for(int i = 0; i < array.length; i++) {  
	            shaHex = Integer.toHexString(array[i] & 0xFF);  
	            if(shaHex.length() < 2) {  
	                hexstr.append(0);  
	            }  
	            hexstr.append(shaHex);  
	        }  
	        return hexstr.toString();  
	    } 
	    
	    /**
	     * 生成签名的时间戳
	     */
	    public static String timeSequenceNo() {
	    	return Long.toString(System.currentTimeMillis() / 1000);
	    }
	    
	    
	    /**
	     * 生成签名的随机串
	     */
	    public static String getSJStr() {
	    	return UUID.randomUUID().toString();
	    }
	         
	    
	    
}
